package com.fowo.api.datainterface.util;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fowo.api.datainterface.aspect.BaseAspect;
import com.fowo.api.datainterface.constants.Constants;
import com.fowo.api.datainterface.constants.DataTypeKind;
import com.fowo.api.datainterface.constants.RequestMethodKind;
import com.fowo.api.datainterface.util.lingxing.LingXingApiSign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 简化领星操作
 *
 * @author dong.tang
 */
@Component
@Slf4j
public class RestUtilLingXing {

	private BaseAspect baseAspect;
	public BaseAspect getBaseAspect() {
		return ObjUtil.isEmpty(baseAspect)?new BaseAspect(DataTypeKind.Lingxing.getValue()):baseAspect;
	}
	/**
	 * 领星接口请求类
	 *
	 * @param requestType "1"代表获取token，"2"代表其他
	 * @param method      请求方式
	 * @param params      请求参数
	 * @param url         请求地址
	 * @param headers     请求头
	 * @return
	 */
	public Object lingXingRequest(String requestType, String method, Map<String, Object> params, String url,Map<String,Object> headers, Map<String, Object> requestBody) {

		//01 验证数据
		if (ObjectUtil.isEmpty(requestType)) {
			Assert.isTrue(false, "是否获取TOKEN标识不能为空");
		}
		if (ObjectUtil.isEmpty(method)) {
			Assert.isTrue(false, "请求方式不能为空");
		}
		if (ObjectUtil.isEmpty(url)) {
			Assert.isTrue(false, "请求地址不能为空");
		}
//		RestTemplate REST_TEMPLATE = new RestTemplate();
		Object result = null;
		//02 发送请求
		if ("1".equals(requestType)) {
			HttpHeaders header = new HttpHeaders();
			header.setContentType(MediaType.APPLICATION_JSON);
			HttpEntity<String> httpEntity = new HttpEntity<String>("", header);
			String path = populateQueryParams(params, url, false);
			result = getBaseAspect().httpRequest(path, HttpMethod.POST, "", header, Object.class, Constants.Read, StrUtil.EMPTY);
//			ResponseEntity<Object> objectResponseEntity = REST_TEMPLATE.postForEntity(s, httpEntity, Object.class);
//			result = objectResponseEntity.getBody();
		} else {
			Map<String, Object> signParam = new HashMap<>();
			signParam.putAll(params);
			if (!CollectionUtils.isEmpty(requestBody)) {
				signParam.putAll(requestBody);
			}
			String sign = LingXingApiSign.sign(signParam, params.get("app_key").toString());
			params.put("sign", sign);
			HttpHeaders header = new HttpHeaders();
//			header.setContentType(MediaType.APPLICATION_JSON);
			if (ObjectUtil.isNotEmpty(headers)) {
				Iterator<Map.Entry<String, Object>> iterator = headers.entrySet().iterator();
				while (iterator.hasNext()) {
					String key = iterator.next().getKey();
					Object value = iterator.next().getValue();
					header.set(key, value.toString());
				}
			}
			String path = populateQueryParams(params, url,true);
			if (StrUtil.equalsIgnoreCase(RequestMethodKind.Get.getValue(), method)) {
				params.putAll(requestBody);
//				path = populateQueryParams(params, url,true);
//				result = REST_TEMPLATE.getForObject(s, Object.class);
				result = getBaseAspect().httpRequest(path, HttpMethod.GET, "", header, Object.class, Constants.Read, StrUtil.EMPTY);
			} else if (StrUtil.equalsIgnoreCase(RequestMethodKind.Post.getValue(), method)) {
//				HttpEntity<String> httpEntity = new HttpEntity<String>(JSONObject.toJSONString(requestBody), header);
//				result = REST_TEMPLATE.postForObject(s, httpEntity, Object.class);
				result = getBaseAspect().httpRequest(path, HttpMethod.POST, JSONObject.toJSONString(requestBody), header, Object.class, Constants.Read, StrUtil.EMPTY);
			} else {
				Assert.isTrue(false, "不支持的请求类型");
			}
		}
		try {
			JSONArray jsonToListMap = JsonUtil.getJsonToJsonArray(result);
			return jsonToListMap;
		} catch (Exception e) {
			try {
				JSONObject map = JsonUtil.getJsonToBean(result, JSONObject.class);
				return map;
			} catch (Exception ee) {
				return result;
			}
		}
	}


	/**
	 * 针对批量sku使用
	 * @param requestType
	 * @param method
	 * @param params
	 * @param url
	 * @param headers
	 * @param requestBody
	 * @return
	 */
	public Object lingXingRequestBatch(String requestType, String method, Map<String, Object> params, String url,Map<String,Object> headers, Map<String, Object> requestBody) {

		//01 验证数据
		if (ObjectUtil.isEmpty(requestType)) {
			Assert.isTrue(false, "是否获取TOKEN标识不能为空");
		}
		if (ObjectUtil.isEmpty(method)) {
			Assert.isTrue(false, "请求方式不能为空");
		}
		if (ObjectUtil.isEmpty(url)) {
			Assert.isTrue(false, "请求地址不能为空");
		}
//		RestTemplate REST_TEMPLATE = new RestTemplate();
		Object result = null;
		//02 发送请求
		if ("1".equals(requestType)) {
			HttpHeaders header = new HttpHeaders();
// 			header.setContentType(MediaType.APPLICATION_JSON);
//			HttpEntity<String> httpEntity = new HttpEntity<String>("", header);
			String path = populateQueryParams(params, url, false);
			result = getBaseAspect().httpRequest(path, HttpMethod.POST, "", header, Object.class, Constants.Read, StrUtil.EMPTY);
//			ResponseEntity<Object> objectResponseEntity = REST_TEMPLATE.postForEntity(s, httpEntity, Object.class);
//			result = objectResponseEntity.getBody();
		} else {
			Map<String, Object> signParam = new HashMap<>();
			signParam.putAll(params);
			if (!CollectionUtils.isEmpty(requestBody)) {
				signParam.putAll(requestBody);
			}
			String sign = LingXingApiSign.signBatch(signParam, params.get("app_key").toString());
			params.put("sign", sign);
			HttpHeaders header = new HttpHeaders();
//			header.setContentType(MediaType.APPLICATION_JSON);
			if (ObjectUtil.isNotEmpty(headers)) {
				Iterator<Map.Entry<String, Object>> iterator = headers.entrySet().iterator();
				while (iterator.hasNext()) {
					String key = iterator.next().getKey();
					Object value = iterator.next().getValue();
					header.set(key, value.toString());
				}
			}
			String path = populateQueryParams(params, url,true);
			if (StrUtil.equalsIgnoreCase(RequestMethodKind.Get.getValue(), method)) {
				params.putAll(requestBody);
				path = populateQueryParams(params, url,true);
				result = getBaseAspect().httpRequest(path, HttpMethod.GET, "", header, Object.class, Constants.Read, StrUtil.EMPTY);
//				result = REST_TEMPLATE.getForObject(s, Object.class);
			} else if (StrUtil.equalsIgnoreCase(RequestMethodKind.Post.getValue(), method)) {
//				HttpEntity<String> httpEntity = new HttpEntity<String>(JSONObject.toJSONString(requestBody), header);
//				result = REST_TEMPLATE.postForObject(s, httpEntity, Object.class);
				result = getBaseAspect().httpRequest(path, HttpMethod.POST, JSONObject.toJSONString(requestBody), header, Object.class, Constants.Read, StrUtil.EMPTY);
			} else {
				Assert.isTrue(false, "不支持的请求类型");
			}
		}
		try {
			JSONArray jsonToListMap = JsonUtil.getJsonToJsonArray(result);
			return jsonToListMap;
		} catch (Exception e) {
			try {
				JSONObject map = JsonUtil.getJsonToBean(result, JSONObject.class);
				return map;
			} catch (Exception ee) {
				return result;
			}
		}
	}

	static String populateQueryParams(Map<String, Object> request, String purl, boolean isEncode) {
		if (request.isEmpty()) {
			return purl;
		}
		StringBuilder url = new StringBuilder(purl);
		url.append("?");
		for (Map.Entry<String, Object> entry : request.entrySet()) {
			try {
				if (isEncode) {
					url.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append("=").append(URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"));
				} else {
					url.append(entry.getKey()).append("=").append(String.valueOf(entry.getValue()));
				}
				url.append("&");
			} catch (UnsupportedEncodingException e) {
			}
		}
		if (url.charAt(url.length() - 1) == '&') {
			url.deleteCharAt(url.length() - 1);
		}
		return url.toString();
	}
}
